import 'package:flutter/material.dart';

class AdaptiveGrid extends StatelessWidget {
  final int itemCount;
  final Function(int) onItemTap;

  const AdaptiveGrid({
    Key? key,
    required this.itemCount,
    required this.onItemTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final double availableWidth = constraints.maxWidth;
        final double boxSize = 100.0; // 每个盒子的理想尺寸
        final double spacing = 16.0; // 盒子之间的间距
        
        int itemsPerRow = (availableWidth / (boxSize + spacing)).floor();
        if (itemsPerRow < 1) itemsPerRow = 1;
        
        final double actualBoxWidth = (availableWidth - (spacing * (itemsPerRow - 1))) / itemsPerRow;
        
        // 计算行数
        final int rowCount = (itemCount / itemsPerRow).ceil();
        
        return SingleChildScrollView(
          child: Column(
            children: List.generate(rowCount, (rowIndex) {
              // 计算这一行的盒子数量
              final int itemsInThisRow = (rowIndex == rowCount - 1 && itemCount % itemsPerRow != 0)
                  ? itemCount % itemsPerRow
                  : itemsPerRow;
              
              return Padding(
                padding: EdgeInsets.only(bottom: spacing),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: List.generate(itemsInThisRow, (colIndex) {
                    final int itemIndex = rowIndex * itemsPerRow + colIndex;
                    return Row(
                      children: [
                        _buildGridItem(actualBoxWidth, itemIndex),
                        if (colIndex < itemsInThisRow - 1) SizedBox(width: spacing),
                      ],
                    );
                  }),
                ),
              );
            }),
          ),
        );
      },
    );
  }

  Widget _buildGridItem(double boxSize, int index) {
    return GestureDetector(
      onTap: () => onItemTap(index),
      child: Container(
        width: boxSize,
        height: boxSize,
        decoration: BoxDecoration(
          color: Colors.primaries[index % Colors.primaries.length],
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              offset: const Offset(0, 2),
              blurRadius: 4,
            ),
          ],
        ),
        child: Center(
          child: Text(
            '${index + 1}',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
} 